<?php

namespace App\Services;

use Firebase\JWT\JWT;
use \Firebase\JWT\Key;
use App\Exceptions\BusinessException;
use App\Http\Response\ResponseEnum;

class JwtService
{
    private $key = 'lottery';

    public function encode(int $user_id)
    {
        $jwt = JWT::encode(
            [
                "iss" => "http://shop.test",
                "aud" => "http://shop.test",
                "iat" => time(),
                "nbf" => time(),
                "exp" => time() + 3600,
                "data" => array(
                    "user_id" => $user_id,
                )
            ],
            $this->key,
            'HS256'
        );

        return $jwt;
    }

    public function decode(string $token)
    {
        try {
            return JWT::decode($token, new Key($this->key, 'HS256'));
        } catch (\Exception $exception) {
            throw new BusinessException(ResponseEnum::CLIENT_HTTP_UNAUTHORIZED, $exception->getMessage());
        }
    }

}

